#include "mypushbutton.h"
#include <QDebug>
#include <QPropertyAnimation>
#include <Qtimer>
void MyPushButton::animation(bool flag)
{
    int beginY = 0;
    int endY = 0;
    if(flag)
        beginY = -10;
    else
        endY = -10;

    // 创建动画对象
    QPropertyAnimation * animation = new QPropertyAnimation(this,"geometry");
    // 设置动画事件间隔
    animation->setDuration(200);
    // 动画开始位置
    animation->setStartValue(QRect(this->x(),this->y()+beginY,this->width(),this->height()));
    // 动画结束位置
    animation->setEndValue(QRect(this->x(),this->y()+endY,this->width(),this->height()));

    // 设置弹跳曲线
    animation->setEasingCurve(QEasingCurve::InQuad);

    // 完成解锁
    connect(animation,&QPropertyAnimation::finished,this,[=](){
        isAnimation = false;

    });
    // 判断是否锁了
    QTimer * timer = new QTimer();
    connect(timer,&QTimer::timeout,this,[=](){
        qDebug() << animation->state() << isAnimation;
        if(!isAnimation){
            isAnimation = true;
            animation->start();
            timer->stop();
        }
    });
    timer->start(100);



}

MyPushButton::MyPushButton(QWidget *parent) : QPushButton(parent)
{

}

MyPushButton::MyPushButton(QString normalImg, QString pressImg)
{
    normalImgPath = normalImg;
    pressImgPath = pressImg;

    QPixmap pixmap;
    bool ret = pixmap.load(normalImgPath);

    if(!ret){
        qDebug() << normalImg << "加载图片失败！";
        return ;
    }
    // 设置图片的固定尺寸
    this->setFixedSize(pixmap.width(),pixmap.height());

    // 设置不规则图片样式
    //  告诉他 按钮的边框是0像素的 有点像css
    this->setStyleSheet("QPushButton{border:0px}");
    // 设置图标
    this->setIcon(QIcon(pixmap));
    // 设置图片大小
    this->setIconSize(QSize(pixmap.width(),pixmap.height()));
    connect(this,&QPushButton::clicked,[=](){
        this->jump();
        this->down();
    });
}

void MyPushButton::jump()
{
    animation(false);
}

void MyPushButton::down()
{
    animation(true);
}

void MyPushButton::mousePressEvent(QMouseEvent *ev)
{
    if(this->isAnimation)
        return ;
    if(pressImgPath != ""){
        QPixmap pixmap;
        bool ret = pixmap.load(pressImgPath);
        if(!ret){
            qDebug() << pressImgPath << "加载图片失败！";
            return ;
        }
        //设置固定尺寸
        this->setFixedSize(pixmap.size());
        // 设置边框
        this->setStyleSheet("QPushButton{border:0px;}");
        // 设置图片
        this->setIcon(QIcon(pressImgPath));
        // 设置图片尺寸
        this->setIconSize(pixmap.size());
    }
    return QPushButton::mousePressEvent(ev);
}

void MyPushButton::mouseReleaseEvent(QMouseEvent *ev)
{
    QPixmap pixmap;
    pixmap.load(normalImgPath);
    // 设置图片固定尺寸
    this->setFixedSize(pixmap.width(),pixmap.height());
    // 设置边框
    this->setStyleSheet("QPushButton{Border:0px;}");
    // 设置图片
    this->setIcon(QIcon(normalImgPath));
    // 设置图片大小
    this->setIconSize(pixmap.size());
    return QPushButton::mouseReleaseEvent(ev);
}
